package net.synck.gcontacts.editor;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPersistableElement;

import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.util.ServiceException;

public class ContactEditorInput implements IEditorInput {

	String gcontactId = null;
	ContactEntry contact = null;	
	
	public ContactEditorInput(String gcontactId) {
		super();
		this.gcontactId = gcontactId;
	}

	public ContactEntry getContactEntry() {
		return contact;
	}
	
	public void setContactEntry(ContactEntry entry) {
		gcontactId = entry.getId();
		contact = entry;
	}
	
	public void checkoutContact(IProgressMonitor monitor) throws IOException, ServiceException {		
		URL contactUrl = null;		
		contactUrl = new URL(getContactId());				
		contact = net.synck.gcontacts.Activator.getDefault().getContactsService()			
			.getEntry(contactUrl, ContactEntry.class );
	}
	
	public void commitContact(IProgressMonitor monitor) throws MalformedURLException, IOException, ServiceException {
		if (contact != null) {
			ContactEntry updatedContact = net.synck.gcontacts.Activator.getDefault().getContactsService()
				.update(new URL(contact.getEditLink().getHref()), contact);
			if (updatedContact != null) {
				contact = updatedContact;
			}
		}		
	}
	
	public String getContactId() {
		return gcontactId;
	}
	
	@Override
	public boolean exists() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public ImageDescriptor getImageDescriptor() {
		return net.synck.gcontacts.Activator.getImageDescriptor("icons/user_edit.png");
	}

	@Override
	public String getName() {
		return gcontactId;
	}

	@Override
	public IPersistableElement getPersistable() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getToolTipText() {
		return "Google contact";
	}

	@Override
	public Object getAdapter(Class adapter) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean equals(Object obj) {
		if (super.equals(obj)) {
			return true;
		}
		if (obj instanceof ContactEditorInput) {
			return gcontactId.equals(((ContactEditorInput) obj).getContactId());			
		}
		return false;
	}

	@Override
	public int hashCode() {
		return gcontactId.hashCode();
	}


	
}
